<?php
/**
 * Created by PhpStorm.
 * User: ZeonWang
 * Date: 2017/4/20
 * Time: 11:41
 */

namespace App\Services\Utils;


use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;

trait FilterWhenable
{

    public function scopeFilterWhenHas(Builder $query, $column, $filter)
    {
        return $query->when(isset($filter) && strlen($filter), function(Builder $query) use($column, $filter){
            return $query->where($column, $filter);
        });
    }

    public function scopeFilterWhenSearch(Builder $query, $column, $filter)
    {
        return $query->when(isset($filter) && strlen($filter), function($query) use($column, $filter){
            return $query->where($column, 'like', '%'.$filter.'%');
        });
    }

    public function scopeFilterWhenIn(Builder $query, $column, $filter)
    {
        if ( ! isset($filter) || ! is_array($filter) ) return $query;

        return $query->when(count($filter), function(Builder $query) use($column, $filter){
            return $query->whereIn($column, $filter);
        });
    }

    public function scopeFilterWhenTime(Builder $query, $start_at, $end_at, $column = 'created_at')
    {
        if ( ! $start_at && ! $end_at) return $query;

        $now = Carbon::now();
        if ( ! $start_at ) {
            $start_at = $now->subYears(10);
        } else {
            $start_at = new Carbon($start_at);
        }

        if ( ! $end_at ) {
            $end_at = $now;
        } else {
            $end_at = new Carbon($end_at);
        }

        return $query->whereBetween($column, [$start_at, $end_at] );
    }
}